using System;
using System.Collections;
using BitMango.Diagnostics;
using UnityEngine;

namespace BitMango
{
	public static class BitMangoRequest
	{
		public static WWW GET(string url, Action<string> callback = null)
		{
			Debugger.Log("BitMangoRequest.Get " + url);
			WWW www = new WWW(url);
			if (callback == null)
			{
				return null;
			}
			TaskRunner.Instance.Run(BitMangoRequest.WaitForRequest(www, callback));
			return www;
		}

		public static WWW GET_Plain(string url, Action<string> callback = null)
		{
			Debugger.Log("BitMangoRequest.GET_Plain " + url);
			WWW www = new WWW(url);
			if (callback == null)
			{
				return null;
			}
			TaskRunner.Instance.Run(BitMangoRequest.WaitForRequestLite(www, callback));
			return www;
		}

		public static IEnumerator WaitForRequestLite(WWW www, Action<string> callback)
		{
			yield return www;
			if (www.error == null)
			{
				if (callback != null)
				{
					callback(www.text);
				}
			}
			else
			{
				Debugger.LogWarning("BitMangoRequest Lite www.error : " + www.error);
				if (callback != null)
				{
					callback(string.Empty);
				}
			}
			yield break;
		}

		private static IEnumerator WaitForRequest(WWW www, Action<string> callback)
		{
			yield return www;
			string decrypted = null;
			if (www.error == null)
			{
				try
				{
					decrypted = Encryptor.Decrypt(www.text);
					Debugger.Log("BitMangoRequest.decrypted : " + decrypted);
				}
				catch (Exception)
				{
					Debugger.LogError("BitMangoRequest.decrypt Fail.. text : " + www.text);
				}
				if (callback != null)
				{
					if (string.IsNullOrEmpty(decrypted))
					{
						callback(string.Empty);
					}
					else
					{
						callback(decrypted);
					}
				}
			}
			else
			{
				Debugger.LogWarning("BitMangoRequest www.error : " + www.error);
				if (callback != null)
				{
					callback(string.Empty);
				}
			}
			yield break;
		}
	}
}
